package Q2;

import java.util.*;

public class Solution {


    public int[] dx = {0, 0, 1, -1};
    public int[] dy = {1, -1, 0, 0};

    public List<Integer> list = new ArrayList<>();

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param CityMap int整型二维数组
     * @param n int整型
     * @param m int整型
     * @return int整型
     */
    public int countPath (int[][] CityMap, int n, int m) {
        // write code here

        int[] start = new int[2];

        for (int i = 0; i < n; i++) {
            boolean flag = false;
            for (int j = 0; j < m; j++) {
                if (CityMap[i][j] == 2) {
                    start[0] = i;
                    start[1] = j;
                    flag = true;
                    break;
                }
            }
            if (flag) {
                break;
            }
        }

        dfs(CityMap, n, m, start[0], start[1], 0, new boolean[n][m]);

        Collections.sort(list);

        int min = list.get(0);
        int count = 0;
        for (int num : list) {
            if (num == min) {
                count++;
            }
        }

        return count;
    }

    public void dfs(int[][] CityMap, int n, int m, int i, int j, int step, boolean[][] flag) {

        if (CityMap[i][j] == 1) {
            list.add(step);
            return;
        }

        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < n && y >= 0 && y < m && !flag[x][y]) {
                flag[x][y] = true;
                dfs(CityMap, n, m, x, y, step + 1, flag);
                //回溯
                flag[x][y] = false;
            }
        }

    }
}